import qs from 'query-string';
import history from '../history';
import React from 'react';

/** 获取 url 参数 */
export const getUrlParameter = (key: string) => {
    return qs.parse(history.location.search)[key] as string || undefined;
}

/** 设置 url 参数 */
export const setUrlParameter = (option: any, isReplace = false) => {
    const sh = qs.parse(history.location.search);
    const path = `${history.location.pathname}?${qs.stringify({ ...sh, ...option })}`;
    isReplace ? history.replace(path) : history.push(path);
}

/** 监听地址栏的参数变化 */
export const useUrlParameter = (key: string, onChange?: () => void) => {

    const [state, setState] = React.useState<string>(qs.parse(history.location.search)[key] as string);

    React.useEffect(onChangeState, [state]); function onChangeState() {
        onChange && onChange()
    }

    React.useEffect(historylisten, []); function historylisten() {
        return history.listen(e => {
            setState(qs.parse(e.search)[key] as string);
        })
    }

    return [state];
}